import React from 'react';
import { browserHistory } from 'react-router'

import avatar from '../img/user/avatar.jpg'
import arrow from '../img/user/arrow.png'
import dashed from '../img/order/dashed.png'
import {ROOTURL,ROOTAPI,customerInfo,fetchFromCommon,fetchFromCommonText,objToForm} from '../../publicAPI/publicAPI.js'
require('../css/FacialmaskUser.css');
class FacialmaskUser extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            phone: '',
            avatar: '',
            dname: '亲爱的小仙女',
            discounts: '',
            showdialog: false,
            sphone: '',
            code: '',
            requestTime: 60,
        }
    }
    componentWillMount(){
    }
    componentDidMount(){
    	let _this=this;
        var getUserInfo=function(){ 
            let { dname,id,phone } = JSON.parse(localStorage.getItem("userInfo"));
            let { avatar } = JSON.parse(localStorage.getItem("customerInfo"));
            _this.setState({
                phone: phone == undefined ? '点击绑定手机号码' : phone
            }) 
            _this.getDiscount(id)
        }
        customerInfo(getUserInfo)
    }
    /*获取未使用的优惠券*/
    getDiscount(id) {
        var url = ROOTAPI+'kabuy/coupon/coupon/search.api'
        fetch(url, {
              method : 'POST',
              mode: 'cors',
              body: JSON.stringify({
                    where: {
                     possessorId: [
                        ['eq', id]
                     ],
                    }
                })
              }).then(res=>{
                  if(res.ok){
                      res.json().then(data=>{
                          this.setState({                       
                            discounts:data  
                          })
                                    
                      })
                 }
      }) 
    }
    toBindPhone() {
        this.setState({
            showdialog: true
        })
    }
    closeDialog() {
        this.setState({
            showdialog: false
        })
    }
    getCode() {
        const phone = this.state.sphone;
        const self = this
        if(!(/^1[3|4|5|7|8]\d{9}$/.test(phone))){
            alert("手机号码有误，请重填")
            return ;
        } else {
            if(this.state.isRequestVeri == true) {

            }else {
                clearInterval(setTime)
                this.setState({isRequestVeri: true})
                var setTime = setInterval(() =>{
                    self.state.requestTime--;
                    if(self.state.requestTime <= 0) {
                        clearInterval(setTime)
                        self.setState({isRequestVeri: false, requestTime: 60})
                        return;
                    }
                    self.setState({requestTime: self.state.requestTime})
                }, 1000)
                if(this.state.requestTime <= 0) {clearInterval(setTime)}
                fetchFromCommon('customer/bind-phone/req-sms.api', 'POST', {phone: phone},
                            (data) => {

                            },
                            (data) => {
                                console.log(data)
                            })
            }
        }
    }
    bindPhone() {
        let code = this.state.code;
        if(this.state.sphone == '' || !(/^1[3|4|5|7|8]\d{9}$/.test(this.state.sphone))) {
            alert("请输入正确手机号码");
        }else {
            if(this.state.code == '') {
                alert("请输入验证码");
            }else {
                let url=ROOTURL + 'customer/bind-phone/do-bind.api'
                fetch(url, {
                      method : 'POST',
                      mode: 'cors',
                      headers: {"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"},
                      credentials: 'include',
                      body: objToForm({code: code})
                      }).then(res=>{
                            if(res.ok) {
                                res.json().then(data=>{
                                    this.bindPhoneSuccess(this.state.sphone);           
                                })
                            }else {
                                res.json().then(data=>{
                                    alert(data.msgl10n)
                                })
                            }
              }) 
            }
        }
        
    }
    bindPhoneSuccess(phone) {
        let customerMsg = JSON.parse(localStorage.getItem('userInfo'));
        customerMsg.phone = phone;
        localStorage.setItem('userInfo', JSON.stringify(customerMsg))

        this.setState({
            showdialog: false,
            phone: phone
        })
    }
    toOrder() {
        browserHistory.push({pathname:`/orderlist`,query:{}})
    }
    toDiscount() {
        browserHistory.push({pathname:`/discount`,query:{}})
    }
    toAddr() {
        browserHistory.push({pathname:`/addr`,query:{}})
    }
    toBuy() {
        browserHistory.push({pathname:`/`,query:{}})
    }
    changePhone(e) {
        const phone = e.target.value
        this.setState({
            sphone: phone
        })
    }
    changeCode(e) {
        const code = e.target.value
        this.setState({
            code: code
        })
    }
    render() {
        return (
            <div className="fm-user">
				<div className="fm-user-table">
					<div className="fm-user-table-title" onClick={this.toBindPhone.bind(this)}>
						<div className="fm-user-table-title-img">
							<img src={avatar}/>
						</div>
						<div className="fm-user-table-title-word">
							<div className="fm-user-table-title-word-name">{this.state.dname}</div>
							<div className="fm-user-table-title-word-phone">手机号：{this.state.phone}</div>
						</div>
						<div className="clear"></div>
					</div>
					<div className="fm-user-table-content">
						<div className="fm-user-table-order" onClick={this.toOrder.bind(this)}>
							<div className="fm-user-table-order-word1">订单</div>
							<div className="arrow"><img src={arrow}/></div>
							<div className="dashed"><img src={dashed}/></div>
							<div className="clear"></div>
						</div>
						<div className="fm-user-table-discount" onClick={this.toDiscount.bind(this)}>
							<div className="fm-user-table-discount-word1">优惠券</div>
							<div className="arrow"><img src={arrow}/></div>
							<div className="fm-user-table-discount-word2">{this.state.discounts.length}张</div>
							<div className="dashed"><img src={dashed}/></div>
							<div className="clear"></div>
						</div>
						<div className="fm-user-table-address" onClick={this.toAddr.bind(this)}>
							<div className="fm-user-table-address-word1">收货地址</div>
							<div className="arrow"><img src={arrow}/></div>
							<div className="fm-user-table-address-word2"></div>
							<div className="dashed"><img src={dashed}/></div>
							<div className="clear"></div>
						</div>
					</div>
				</div>
				<div className="fm-user-button" onClick={this.toBuy.bind(this)}>
					去下单
				</div>
                {this.state.showdialog == true?
                    <div className="fm-user-dialog">
                        <div className="fm-user-dialog-mask"></div>
                        <div className="fm-user-dialog-content">
                            <span className="fm-user-dialog-close" onClick={this.closeDialog.bind(this)}>&#215;</span>
                            <div className="clear"></div>
                            <div className="fm-user-dialog-row">
                                <label>手机号:</label><input type="text" name="phone" onChange={(e) => this.changePhone(e)}/>
                            </div>
                            <div className="fm-user-dialog-row">
                                <label>验证码:</label><input type="text" name="code"  onChange={(e) => this.changeCode(e)} style={{width:"37%",left:"29%"}}/><span onClick={this.getCode.bind(this)} className="fm-user-dialog-row-code">{this.state.isRequestVeri ? (this.state.requestTime + '秒重新发送') : "获取验证码"}</span>
                            </div>
                            <div className="fm-user-dialog-row-submit" onClick={this.bindPhone.bind(this)}>
                                提交
                            </div>
                        </div>
                    </div>:''
                }
            </div>
        )
    }
}


export default FacialmaskUser;